<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { dictFormSchema } from './dict.data'
import { addorUpdateDictItem } from '@/api/sys/dict';

defineOptions({ name: 'DictModal' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(true)
const dictCode = ref()
const rowId = ref('')

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: dictFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  dictCode.value = data?.dictCode
  if (unref(isUpdate)) {
    console.log(data);
    rowId.value = data.record.itemId
    setFieldsValue({
      ...data.record,
    })
  }

  // const treeData = await getOrganizationTree()
  // updateSchema([
  //   {
  //     field: 'pwd',
  //     show: !unref(isUpdate),
  //   },
  //   {
  //     field: 'name',
  //     componentProps: { treeData: [treeData] },
  //   },
  // ])
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增字典项' : '编辑字典项'))

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    let params: any = { ...values, dictCode: unref(dictCode) }
    if (unref(isUpdate)) {
      params = { ...params, itemId: rowId.value, dictCode: dictCode.value }
    }
    await addorUpdateDictItem(params)
    closeModal()
    // 修改也重新加载数据，如果修改了 index，后端会根据 index 对表格进行排序
    emit('success', { values: { ...values, id: rowId.value } })
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>
